package com.carkeeper.gateway.filter;

import com.carkeeper.gateway.service.AuthService;
import com.carkeeper.gateway.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author Administrator
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    public static final String LOGIN_URL = "http://localhost:8001/api/oauth/toLogin";

    @Autowired
    private AuthService authService;

    /**
     * 1）判断当前请求是否为登录请求，是的话，则放行
     * <p>
     * 2) 判断cookie中是否存在信息, 没有的话，拒绝访问
     * <p>
     * 3）判断redis中令牌是否存在，没有的话，拒绝访问
     * <p>
     * 实现当用户没有携带令牌过来访问时 拒绝访问
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断当前请求是否为登录请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();

        //2判断请求路径中是否包含登录请求或者去登录的请求
        if (path.contains("/api/admin/login") || path.contains("/api/admin/toLogin") || !UrlFilter.hasAuthorize(path)) {
            //放行
            return chain.filter(exchange);
        }

        //3否则，判断cooki中是否存在信息，没有的话，拒绝访问
        String uuId = authService.getJtiFromCookie(request);


        //没有则拒绝访问
        if (StringUtils.isBlank(uuId)) {

           // return this.toLoginPage(LOGIN_URL + "?FROM=" + path, exchange);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.判断redis中令牌是否存在，没有的话，拒绝访问

        String token = authService.getTokenFromRedis(uuId);

        //拒绝访问
        if (StringUtils.isBlank(token)) {
          //  return toLoginPage(LOGIN_URL + "?FROM=" + path, exchange);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //解析令牌
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //10. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //11. 返回
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 使用户没有登录访问时跳转登录页面
     *
     * @param
     * @param
     * @return
     */
  /*  private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {

        ServerHttpResponse response = exchange.getResponse();

        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", loginUrl);

        return response.setComplete();
    }*/

    @Override
    public int getOrder() {
        return 0;
    }


}
